﻿using BusinessEntity;
using BusinessEntity.Warning;
using learun.util;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{

    public class JavaApi
    {
        //static bool protxt = false;
        static bool protxt = ConfigHelper.GetAppSettings("ServerOp:test") == "1";

        public static string HttpPost(string url, string body)
        {
            using (var httpClient = new HttpClient())
            {
                var url1 = new Uri(url + "?" + body);
                // response
                var response = httpClient.GetAsync(url1).Result;
                var data = response.Content.ReadAsStringAsync().Result;
                return data;//接口调用成功获取的数据
            }
        }

        public static string GetIpAddress1(string url)
        {
            if (protxt)
            {
                url = $"{url}/oauth/check_token";
                url = url.Replace("172.31.162.64:3000", "118.190.140.38:3000");
            }
            else
            {
                url = $"{url}/oauth/check_token";
            }
            return url;
        }
        public static string GetIpAddress(string url)
        {
            if (protxt)
            {
                //url = $"{url}/dept/list/role-permission";
                // url = $"{url}/admin/dept/scope/list";
                url = $"{url}/admin/dept/list/";
                //118.190.140.38:5052/admin/dept/list/project_permission
                url = url.Replace("172.31.162.64:4000", "118.190.140.38:9999");
                url = url.Replace("118.190.140.38:4000", "118.190.140.38:9999");
            }
            else
                //url = $"{url}/dept/list/role-permission";
                //url = $"{url}/dept/scope/list";
                url = $"{url}/dept/list/";
            return url;
        }

        //public static string GetIpAddress(string url)
        //{
        //    if (protxt)
        //    {
        //        //url = $"{url}/dept/list/role-permission";
        //        url = $"{url}/admin/dept/list/";
        //        //118.190.140.38:5052/admin/dept/list/project_permission
        //        url = url.Replace("172.31.162.64:4000", "118.190.140.38:5052");
        //        url = url.Replace("172.31.162.64:6500", "118.190.140.38:4053/mock/29");
        //    }
        //    else
        //        //url = $"{url}/dept/list/role-permission";
        //        url = $"{url}/dept/list/";
        //    return url;
        //}

        //审批状态
        public static string GetIpAddress2(string url)
        {
            if (protxt)
                url = "http://118.190.140.38/api/ic-business/task/getTodo";
            else
            {
                url = $"{url}/task/getTodo";
            }
            return url;
        }

        //审批状态
        public static string GetIpAddressDB(string url)
        {
            if (protxt)
                url = "http://118.190.140.38/api/ic-business/task/getTodo";
            else
            {
                url = $"{url}/task/getTodo";
            }
            return url;
        }

        //预警地址
        public static string GetIpAddressWarn(string url)
        {
            if (protxt)
                url = "http://118.190.140.38:9999/warn-monitoring/monitor/business/list  ";
            else
            {
                url = $"{url}/monitor/business/list";
            }
            return url;
        }

        public static string GetIpAddressBM(string url)
        {
            if (protxt)
                url = "http://118.190.140.38:5052/ic-business/number-rule/next";
            else
                url = $"{url}/number-rule/next";
            return url;
        }

        //附件上传
        public static string GetIpAddress4(string url)
        {
            if (protxt)
                url = "http://118.190.140.38:5052/ic-business/business-file/batch";
            else
                url = $"{url}/business-file/batch";
            return url;
        }
        public static string GetIpAddress5(string url)
        {
            if (protxt)
                url = "http://118.190.140.38/api/ic-business/ic-inner-pangu/startInstance";
            else
                url = $"{url}/ic-inner-pangu/startInstance";
            return url;
        }

        public static string GetIpAddress6(string url)
        {
            // ic-upms/dict/type
            if (protxt)
                url = "http://118.190.140.38:5052/admin/dict/v2/type/";
            else
                url = $"{url}/dict/v2/type/";
            return url;
        }


        public static string GetIpAddress7(string url)
        {
            if (protxt)
                url = "http://118.190.140.38:9999/ic-business/CommonFormCardType/getByCode/";
            else
                url = $"{url}/CommonFormCardType/getByCode/";
            return url;
        }

        public static string GetIpAddress10(string url)
        {
            if (protxt)
            {
                url = $"{url}/auth/oauth/token?grant_type=password";
                url = url.Replace("172.31.162.64:3000", "118.190.140.38:5052");
            }
            else
            {
                url = $"{url}/oauth/token?grant_type=password";
            }
            return url;
        }



        #region 部门权限
        //List<DataItem> data
        public static async Task<List<DataItem>> GetDepInfo(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                Logger _logger = LogManager.GetCurrentClassLogger();
                List<DataItem> dataItems = new List<DataItem>();
                //string strdepids = "(";
                //string baseUrl = await GetIcUrl(serviceName);

                //string strAuthorization = GetAuthorization();

                //var url = $"{baseUrl}/dept/list/role-permission";
                var url = $"{baseUrl}/dept/list/";
                _logger.Log(LogLevel.Info, "路径:" + url);
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = GetIpAddress(baseUrl) + permission;
                    // url = GetIpAddress(baseUrl);//permission

                    _logger.Log(LogLevel.Info, "路径:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "返回的数据:" + result);
                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<DepRoot>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (Jresult.code == "200" && null != Jresult && null != Jresult.data)
                        {
                            dataItems = Jresult.data.FindAll(l =>
                            {
                                return l.delFlag == "0";
                            });
                        }
                    }
                }

                return dataItems;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        public static async Task<List<DataItem>> getDescendantListinfo(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                Logger _logger = LogManager.GetCurrentClassLogger();
                List<DataItem> dataItems = new List<DataItem>();

                //string strdepids = "(";
                //string baseUrl = await GetIcUrl(serviceName);

                //string strAuthorization = GetAuthorization();

                //var url = $"{baseUrl}/dept/list/role-permission";
                var url = $"{baseUrl}/dept/getDescendantList/";
                _logger.Log(LogLevel.Info, "路径:" + url);
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                    url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission;
                    _logger.Log(LogLevel.Info, "路径:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "返回的数据:" + result);
                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<DepRoot>(result);// result.ToJson();

                        // Jresult.data.Count
                        if (Jresult.code == "200" && null != Jresult && null != Jresult.data)
                        {
                            dataItems = Jresult.data.FindAll(l =>
                            {
                                return l.ancestor == permission;
                            });

                        }
                    }
                }

                return dataItems;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static async Task<string> GetDepId(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                string strdepids = "(";
                List<DataItem> list = await GetDepInfo(permission, baseUrl, strAuthorization);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].delFlag == "0")
                        strdepids += "'" + list[i].deptId + "',";
                }

                strdepids = strdepids.TrimEnd(',');
                strdepids += ")";
                return strdepids == "()" ? "('')" : strdepids;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static async Task<string> GetDepCode(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                string strdepids = "(";
                List<DataItem> list = await GetDepInfo(permission, baseUrl, strAuthorization);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].delFlag == "0")
                        strdepids += "'" + list[i].code + "',";
                }

                strdepids = strdepids.TrimEnd(',');
                strdepids += ")";
                return strdepids == "()" ? "('')" : strdepids;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static async Task<string> getDescendantList(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                string strdepids = "(";
                List<DataItem> list = await getDescendantListinfo(permission, baseUrl, strAuthorization);
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].ancestor == permission)
                        strdepids += "'" + list[i].descendant + "',";
                }

                strdepids = strdepids.TrimEnd(',');
                strdepids += ")";
                return strdepids == "()" ? "('')" : strdepids;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        public static async Task<string> GetOrgs(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                Logger _logger = LogManager.GetCurrentClassLogger();
                _logger.Log(LogLevel.Info, "路径:" + baseUrl);
                string org = "";
                int len = 0;
                List<DataItem> list = await GetDepInfo(permission, baseUrl, strAuthorization);
                _logger.Log(LogLevel.Info, "返回的数据:" + list.ToString());
                foreach (DataItem item in list)
                {
                    if (org == "")
                    {
                        if (item.code != "system")
                        {
                            if (ConfigHelper.GetConfig().areacode == "096")//园区
                            {
                                if (item.code.Contains("320571"))
                                {
                                    org = item.code;
                                    continue;
                                }
                                else
                                {
                                    if (item.code.Contains("9999"))
                                    {
                                        org = item.code;
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                if (item.code.Contains("320508"))//姑苏区
                                {
                                    org = item.code;
                                    continue;
                                }

                            }
                        }
                    }
                    if (org.Contains("3205"))
                    {

                        if (org.Length > 0 && org.Length > item.code.Length && item.code.Length > 6)
                        {
                            if (ConfigHelper.GetConfig().areacode == "096")//园区
                            {
                                if (item.code.Contains("320571"))
                                {
                                    org = item.code;
                                }
                            }
                            else
                            {
                                if (item.code.Contains("320508"))//姑苏区
                                {
                                    org = item.code;
                                }
                            }
                        }
                        else if (org.Length > item.code.Length)
                        {
                            if (ConfigHelper.GetConfig().areacode == "096")//园区
                            {
                                if (item.code.Contains("320571"))
                                {
                                    org = item.code;
                                }
                            }
                            else
                            {
                                if (item.code.Contains("320508"))//姑苏区
                                {
                                    org = item.code;
                                }
                            }
                        }
                    }

                }

                _logger.Log(LogLevel.Info, "返回的org:" + org);
                return org;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static async Task<string> GetOrg(string permission, string url, string strAuthorization)
        {
            string org = "";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission;
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    //_logger.Log(LogLevel.Info, "返回的数据:" + url);
                    if (result.Contains("\"code\":1"))
                    {
                        _logger.Log(LogLevel.Info, "数据:" + result);
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                         _logger.Log(LogLevel.Info, "返回的数据:" + result);
                        //var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<DepRoot>(result);// result.ToJson();
                        int len = 0;
                        JObject jb = JObject.Parse(result);
                        string scode = jb["code"].ToString();
                        JArray ja = JArray.Parse(jb["data"].ToString());
                        // _logger.Log(LogLevel.Info, "返回的数据:" + ja.ToString());
                        //Jresult.data.Count
                        if (scode == "200" && ja != null)
                        {
                            //org = Jresult.data[0].code;
                            foreach (JObject item in ja)
                            {
                                if (jb.Property("code") != null && item["code"].ToString() != "system")
                                {
                                    if (org == "")
                                    {
                                        _logger.Log(LogLevel.Info, "组织代码:" + item.ToString());
                                        _logger.Log(LogLevel.Info, "组织代码:" + item["code"].ToString());
                                        string o = item["code"].ToString();
                                        _logger.Log(LogLevel.Info, "组织代码:" + o);
                                        if (ConfigHelper.GetConfig().areacode == "096")
                                        {
                                            if (o.Contains("320571"))
                                            {
                                                org = o;

                                                continue;
                                            }
                                        }
                                        else
                                        {
                                            if (o.Contains("320508"))
                                            {
                                                org = o;

                                                continue;
                                            }
                                        }
                                    }


                                    if (org.Length > 0 && org.Length > item["code"].ToString().Length && item["code"].ToString().Length > 6)
                                    {
                                        org = item["code"].ToString();
                                    }

                                }

                            }
                            //if (!org.Contains("320508") && org.Length < 6)
                            //{
                            //    org = "320508";
                            //}
                        }
                        else
                        {
                            org = "";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return org;
        }

        public static async Task<string> GetOrgCode(string permission, string url, string strAuthorization)
        {
            string org = "(";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission;
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    //_logger.Log(LogLevel.Info, "返回的数据:" + url);
                    if (result.Contains("\"code\":1"))
                    {
                        _logger.Log(LogLevel.Info, "数据:" + result);
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        //_logger.Log(LogLevel.Info, "返回的数据:" + result);
                        //var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<DepRoot>(result);// result.ToJson();
                        int len = 0;
                        JObject jb = JObject.Parse(result);
                        string scode = jb["code"].ToString();
                        JArray ja = JArray.Parse(jb["data"].ToString());
                        // _logger.Log(LogLevel.Info, "返回的数据:" + ja.ToString());
                        //Jresult.data.Count
                        if (scode == "200" && ja != null)
                        {
                            //org = Jresult.data[0].code;
                            foreach (JObject item in ja)
                            {
                                if (jb.Property("code") != null)
                                {
                                    org += "'"+ item["code"].ToString() + "',";
                                    _logger.Log(LogLevel.Info, "返回的单位:" + org);
                                }

                            }
                            if (org.Contains(","))
                            {
                                org = org.Substring(0, org.Length - 1) + ")";
                                _logger.Log(LogLevel.Info, "返回的单位:" + org);
                            }
                        }
                        else
                        {
                            org = "";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return org;
        }

        public static async Task<string> GetJavaPZ(string permission, string url, string strAuthorization, string org, string start, string end, int current, int size)
        {
            string json = "";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission + "?org=" + org + "&start=" + start + "&end=" + end + "&current=" + current + "&size=" + size + "";
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "收到的数据：" + result);
                    json = result;
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return json;
        }

        public static async Task<string> GetJavaPZInfo(string permission, string url, string strAuthorization, string id)
        {
            string json = "";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission + id;
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "收到的数据：" + result);
                    json = result;
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return json;
        }

        public static async Task<string> GetJavaBudgets(string permission, string url, string strAuthorization, string org, string month, int current, int size)
        {
            string json = "";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission + "?org=" + org + "&month=" + month + "&current=" + current + "&size=" + size + "";
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "收到的数据：" + result);
                    json = result;
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return json;
        }
        public static async Task<string> GetJavaBudgetsInfo(string permission, string url, string strAuthorization, string id)
        {
            string json = "";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission + id;
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "收到的数据：" + result);
                    json = result;
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return json;
        }

        public static async Task<string> GetJavaZC(string permission, string url, string strAuthorization, string org)
        {
            string json = "";
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //_logger.Log(LogLevel.Info, "调用的URL:" + url);
                    //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                    url = url + permission + "?org=" + org;
                    _logger.Log(LogLevel.Info, "调用的URL:" + url);
                    var response = await client.GetAsync(url);

                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;
                    _logger.Log(LogLevel.Info, "收到的数据：" + result);
                    json = result;
                }
            }
            catch (Exception e)
            {
                _logger.Log(LogLevel.Info, "错误" + e.Message);
            }
            return json;
        }

        public static void GetParentNodes(List<DataItem> list, List<DataItem> listoo, string pid)
        {
            //if (pid != "0")
            {
                for (int i = 0; i < list.Count; i++)
                {
                    //如果当前节点是单位不是部门 ，取父节点
                    if (list[i].delFlag == "0" && list[i].deptId == pid)
                    {
                        if (!listoo.Contains(list[i]))
                        {
                            listoo.Add(list[i]);
                            GetParentNodes(list, listoo, list[i].parentId);
                        }
                    }
                }
            }
        }

        public static void GetAllParentNodes(List<DataItem> listAll, List<DataItem> listHas, List<DataItem> listSource, string pid)
        {
            for (int i = 0; i < listAll.Count; i++)
            {
                if (listAll[i].deptId == pid)
                {
                    if (!listSource.Contains(listAll[i]))
                    {
                        listAll[i].Locks = "0";
                        if (!listHas.Contains(listAll[i]))
                        {
                            listAll[i].Locks = "1";
                        }
                        listSource.Add(listAll[i]);
                        GetAllParentNodes(listAll, listHas, listSource, listAll[i].parentId);
                    }
                }
            }
        }

        public static async Task<DataItem> GetDepIDInfoSig(string dwmc, string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                List<DataItem> listAll = await GetDepInfoList(permission, baseUrl, strAuthorization);

                var find = listAll.Find(di =>
                {
                    return di.name == dwmc;
                });


                return find;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static async Task<DataItem> GetDepInfoSig(string dwid, string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                List<DataItem> listAll = await GetDepInfoList(permission, baseUrl, strAuthorization);

                var find = listAll.Find(di =>
                {
                    return di.deptId == dwid;
                });


                return find;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static async Task<List<DataItem>> GetDepInfoList(string permission, string baseUrl, string strAuthorization)
        {
            try
            {
                List<DataItem> listAll = await GetDepInfo(permission, baseUrl, strAuthorization);

                return listAll;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static async Task<IEnumerable<dynamic>> GetDepInfoTree(string strlx, string dwmc, string permission, string baseUrl, string strAuthorization)
        {
            try
            {

                List<DataItem> listAll = await GetDepInfo(permission, baseUrl, strAuthorization);

                List<DataItem> listHas = new List<DataItem>();

                List<DataItem> listNull = new List<DataItem>();
                for (int i = 0; i < listAll.Count; i++)
                {
                    //如果当前节点是单位不是部门 ，取父节点
                    if (listAll[i].delFlag == "0")//&& listAll[i].type == "unit"
                    {
                        if (strlx != "unit" || (strlx == "unit" && listAll[i].type == "unit"))
                        {
                            if (string.IsNullOrEmpty(dwmc) || (!string.IsNullOrEmpty(dwmc) && listAll[i].name.Contains(dwmc)))
                            {
                                if (!listHas.Contains(listAll[i]))
                                {
                                    //默认的不锁
                                    listAll[i].Locks = "0";
                                    listHas.Add(listAll[i]);

                                    //GetParentNodes(listAll, listoo, listAll[i].parentId);
                                }
                            }
                        }
                    }
                }

                List<DataItem> listoo1 = new List<DataItem>();
                for (int i = 0; i < listHas.Count; i++)
                {
                    if (!listoo1.Contains(listHas[i]))
                    {
                        listoo1.Add(listHas[i]);

                        GetAllParentNodes(listAll, listHas, listoo1, listHas[i].parentId);
                    }
                }


                listNull = listoo1;

                List<dynamic> listr = new List<dynamic>();
                for (int i = 0; i < listNull.Count; i++)
                {
                    string deptid = listNull[i].deptId;
                    //unit
                    if (listNull[i].delFlag == "0" && listNull[i].parentId == "0")
                    {
                        listr.Add(listNull[i]);

                        //绑定子节点
                        GetChildNodes(listNull[i], listNull, deptid);
                    }
                }
                return listr;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static void GetChildNodes(dynamic d, List<DataItem> list, string pid)
        {
            List<dynamic> listr = new List<dynamic>();
            for (int i = 0; i < list.Count; i++)
            {
                string deptid = list[i].deptId;
                if (list[i].delFlag == "0" && list[i].parentId == pid)
                {
                    listr.Add(list[i]);

                    //绑定子节点
                    GetChildNodes(list[i], list, deptid);
                }
            }
            d.childs = listr;
        }

        public class DataItem
        {
            /// <summary>
            /// 
            /// </summary>
            public string deptId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public double sort { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string createTime { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string updateTime { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string parentId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string delFlag { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string type { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }

            public string Locks { get; set; }

            //助记码
            public string mnemonicCode { get; set; }


            //这里加一个参数
            public List<dynamic> childs;
            public string ancestor { get; set; }
            public string descendant { get; set; }
        }


        public class DepRoot
        {
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<DataItem> data { get; set; }
        }


        #endregion

        #region 业务编码
        public static async Task<string> BusinessBMJavaAPI(string type, string json, (string, string) apiinfo)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            _logger.Trace("=====================业务编码=============================================");
            _logger.Trace((type, json));

            if (string.IsNullOrEmpty(json))
            {
                json = "{}";
            }

            FileReqBM bm = new FileReqBM();
            bm.type = type;
            bm.jsonStr = json;

            if (string.IsNullOrEmpty(type))
            {
                //throw new Exception("文件上传接口，必填项code|version校验不通过。"); //return result;
                return "";
            }

            try
            {
                string baseUrl = apiinfo.Item1;
                string strAuthorization = apiinfo.Item2;

                List<DataItem> dataItems = new List<DataItem>();


                var url = $"{baseUrl}/ic-business/number-rule/next";



                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //url = "http://118.190.140.38:5052/ic-business/number-rule/next";
                    url = GetIpAddressBM(baseUrl);

                    _logger.Trace("地址：" + url);

                    string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(bm);
                    var data = Encoding.UTF8.GetBytes(sdata);
                    var content = new ByteArrayContent(data);
                    //application/x-www-form-urlencoded
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await client.PostAsync(url, content);


                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;

                    _logger.Trace(result);

                    if (result == "{}")//暂时
                    {
                        return "";
                    }
                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<FileResBM>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (null != Jresult && Jresult.code == "200")
                        {
                            _logger.Trace("=====================编码成功=============================================");
                            return Jresult.data.ToString();
                        }
                        else
                            return "";
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);
                _logger.Trace("=====================编码失败=============================================");
                throw new Exception(ex.Message);
            }
        }
        public class FileReqBM
        {
            public string type { get; set; }
            public string jsonStr { get; set; }
        }

        public class FileResBM
        {
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public object data { get; set; }
        }
        #endregion

        #region 附件上传
        public static async Task<bool> UploadFileJavaAPI(string ywid, FileUploadent files, (string, string) apiinfo)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            _logger.Trace("=====================附件上传=============================================");
            _logger.Trace((ywid, Newtonsoft.Json.JsonConvert.SerializeObject(files)));

            files.businessId = ywid;

            //xdl 20210721 前端没有s 后端接口有s
            files.deleteFileIds = files.deleteFileId;
            files.deleteFileId = null;

            //如果没有附件 并且没有删除 附件直接跳过
            //if ((null == files.fileCodes || files.fileCodes.Count == 0) && (null == files.deleteFileIds || files.deleteFileIds.Count == 0))
            //{
            //    return true;
            //}

            if (string.IsNullOrEmpty(files.code) || string.IsNullOrEmpty(files.version))//|| null == files.fileCodes || null == files.deleteFileIds
            {
                //throw new Exception("文件上传接口，必填项code|version校验不通过。"); //return result;
                return true;
            }

            try
            {
                string baseUrl = apiinfo.Item1;
                string strAuthorization = apiinfo.Item2;

                List<DataItem> dataItems = new List<DataItem>();

                //url = "http://118.190.140.38:4053/mock/113/ic-business/business-file/batch";
                //http://118.190.140.38:5052/ic-business/business-file/batch

                var url = $"{baseUrl}/ic-business/business-file/batch";



                using (HttpClient client = new HttpClient())
                {
                    string clientInfo = "test:test";
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(clientInfo);
                    clientInfo = Convert.ToBase64String(bytes, Base64FormattingOptions.None);

                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    //url = "http://118.190.140.38:5052/ic-business/business-file/batch";
                    url = GetIpAddress4(baseUrl);

                    _logger.Trace("地址：" + url);

                    string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(files);
                    var data = Encoding.UTF8.GetBytes(sdata);
                    var content = new ByteArrayContent(data);
                    //application/x-www-form-urlencoded
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await client.PostAsync(url, content);


                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;

                    _logger.Trace(result);

                    if (result == "{}")//暂时
                    {
                        return true;
                    }
                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<FileRes>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (Jresult.code == "200" && null != Jresult)
                        {
                            _logger.Trace("=====================附件成功=============================================");
                            return true;
                        }
                        else
                            return false;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);
                _logger.Trace("=====================附件失败=============================================");
                throw new Exception(ex.Message);
            }
        }
        public class FileRes
        {
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public object data { get; set; }
        }
        #endregion

        #region 发起审批流
        public static async Task<string> startInstanceJavaAPIStr(SPLEnt spl, (string, string) apiinfo)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                _logger.Trace("=====================发起审批=============================================");
                _logger.Trace(Newtonsoft.Json.JsonConvert.SerializeObject(spl));

                if (string.IsNullOrEmpty(spl.formCode))
                {
                    throw new Exception("提交审批接口，必填项formcode校验不通过。"); //return result;
                }

                _logger.Trace("======判断有无审批=======");
                //string strstatus = await GetFormCodeHasJavaAPI(spl.formCode, apiinfo);
                string strstatus = "has";
                _logger.Trace(strstatus);
                _logger.Trace("======判断有无审批=======");
                if (strstatus == "has")
                {
                    string baseUrl = apiinfo.Item1;
                    string strAuthorization = apiinfo.Item2;

                    var url = $"{baseUrl}/api/ic-business/ic-inner-pangu/startInstance";
                    //url = "http://118.190.140.38/api/ic-business/ic-inner-pangu/startInstance";

                    url = GetIpAddress5(baseUrl);

                    _logger.Trace(url);

                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                        string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(spl);
                        _logger.Trace(sdata);

                        var data = Encoding.UTF8.GetBytes(sdata);
                        var content = new ByteArrayContent(data);
                        content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                        var response = await client.PostAsync(url, content);


                        //获取请求到数据，并转化为字符串
                        var result = response.Content.ReadAsStringAsync().Result;

                        _logger.Trace("收到的回文：" + result);

                        if (result.Contains("\"code\":1"))
                        {
                            throw new Exception(result); //return result;
                        }
                        else
                        {
                            var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<AuditRoot>(result);// result.ToJson();
                            if (Jresult.code == 200 && null != Jresult && null != Jresult.data)
                            {
                                //Jresult.data.processInstanceId;
                                _logger.Trace("=====================发起审批结束=======================================");

                                return Jresult.data.processInstanceId;
                            }
                            else
                            {
                                return "err";
                            }
                        }
                    }
                }
                else if (strstatus == "hasno")
                {
                    return "errhasno";
                }
                else
                {
                    return "err1";
                }
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);

                _logger.Trace("=====================发起审批结束=============================================");
                throw new Exception(ex.Message);
            }
        }

        public static async Task<bool> startInstanceJavaAPI(SPLEnt spl, (string, string) apiinfo)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                _logger.Trace("=====================发起审批=============================================");
                _logger.Trace(Newtonsoft.Json.JsonConvert.SerializeObject(spl));

                if (string.IsNullOrEmpty(spl.formCode))
                {
                    throw new Exception("提交审批接口，必填项formcode校验不通过。"); //return result;
                }

                _logger.Trace("======判断有无审批=======");
                //string strstatus = await GetFormCodeHasJavaAPI(spl.formCode, apiinfo);
                string strstatus = "has";
                _logger.Trace(strstatus);
                _logger.Trace("======判断有无审批=======");
                if (strstatus == "has")
                {
                    string baseUrl = apiinfo.Item1;
                    string strAuthorization = apiinfo.Item2;

                    var url = $"{baseUrl}/api/ic-business/ic-inner-pangu/startInstance";
                    //url = "http://118.190.140.38/api/ic-business/ic-inner-pangu/startInstance";

                    url = GetIpAddress5(baseUrl);

                    _logger.Trace(url);

                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                        string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(spl);
                        var data = Encoding.UTF8.GetBytes(sdata);
                        var content = new ByteArrayContent(data);
                        content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                        var response = await client.PostAsync(url, content);


                        //获取请求到数据，并转化为字符串
                        var result = response.Content.ReadAsStringAsync().Result;

                        _logger.Trace(result);

                        if (result.Contains("\"code\":1"))
                        {
                            throw new Exception(result); //return result;
                        }
                        else
                        {
                            var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<AuditRoot>(result);// result.ToJson();
                            if (Jresult.code == 200 && null != Jresult && null != Jresult.data)
                            {
                                //Jresult.data.processInstanceId;
                                _logger.Trace("=====================发起审批结束=======================================");

                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
                else if (strstatus == "hasno")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);

                _logger.Trace("=====================发起审批结束=============================================");
                throw new Exception(ex.Message);
            }
        }

        public class Data
        {
            /// <summary>
            /// 
            /// </summary>
            public string id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string processInstanceId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string businessId { get; set; }
            /// <summary>
            /// 投资计划结转
            /// </summary>
            public string businessName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string callbackInterface { get; set; }
            /// <summary>
            /// |||||||{}
            /// </summary>
            public string description { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string formCode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string taskId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string taskDefKey { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string taskName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string previousTaskDefKey { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string approveUser { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string dealUser { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string urgeStatus { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string approveStatus { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string callbackUrl { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string createTime { get; set; }
        }

        public class AuditRoot
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Data data { get; set; }
        }



        public class SPLEnt
        {
            public SPLEnt()
            { }
            public SPLEnt(string _businessName, string _businessId, string _formcode, string _additionInfoJson, string _callbackUrl)
            {
                businessName = _businessName;
                businessId = _businessId;
                formCode = _formcode;
                additionInfoJson = _additionInfoJson;
                callbackUrl = _callbackUrl;


                //businessName = _businessName;
            }

            public SPLEnt(string _businessName, string _businessId, string _formcode, string _additionInfoJson, string _callbackUrl, string _callbackInterface, string _callbackView, Auditdescription _description)
            {
                businessName = _businessName;
                businessId = _businessId;
                formCode = _formcode;
                additionInfoJson = _additionInfoJson;
                callbackUrl = _callbackUrl;
                //businessName = _businessName;

                callbackInterface = _callbackInterface;

                callbackView = _callbackView;

                description = _description.ToJson();
            }

            public string GetDOURL(string _businessName)
            {
                string url = BaseEditPower.SPDetailUrl[_businessName];
                url.Replace("", ":");
                return "";
            }

            /// <summary>
            /// 业务名(表明)
            /// </summary>
            public string businessName { get; set; }
            /// <summary>
            /// 业务id(业务id)
            /// </summary>
            public string businessId { get; set; }
            /// <summary>
            /// 参数字典的key值，存储流程定义信息的id，见字典管理中process_definition_info
            /// </summary>
            //public string publicParamKey { get; set; }
            /// <summary>
            /// 业务模块
            /// </summary>
            public string formCode { get; set; } = "quota_detail";
            /// <summary>
            /// 业务关键字描述
            /// </summary>
            public string description { get; set; }
            /// <summary>
            /// 业务表单信息（用于流程流转）
            /// </summary>
            public string additionInfoJson { get; set; }
            /// <summary>
            /// 回调url(短域名)
            /// </summary>
            public string callbackUrl { get; set; }
            /// <summary>
            /// 审批详情页
            /// </summary>
            public string callbackInterface { get; set; }

            /// <summary>
            /// 已办详情页
            /// </summary>
            public string callbackView { get; set; }

            public string deptId { get; set; }
            public string deptCode { get; set; }


            public class Auditdescription
            {
                /// <summary>
                /// 
                /// </summary>
                public string businessNo { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string amount { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string deptName { get; set; }

                public string content { get; set; }
            }

        }




        #endregion

        #region 获取字典
        public static async Task<List<DataItemDIC>> GetDicJavaAPI(string formid, (string, string) apiinfo)
        {
            try
            {
                if (string.IsNullOrEmpty(formid))
                {
                    throw new Exception("获取字典失败，必填项(字典描述)校验不通过。"); //return result;
                }

                List<DataItemDIC> list = new List<DataItemDIC>();

                string baseUrl = apiinfo.Item1;
                string strAuthorization = apiinfo.Item2;

                var url = $"{baseUrl}/admin/dict/type/";//protect_section_type

                //url = "http://118.190.140.38:5052/admin/dict/type/" + formid;

                url = GetIpAddress6(baseUrl) + formid;


                using (HttpClient client = new HttpClient())
                {
                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                    var result = await client.GetStringAsync(url);


                    //获取请求到数据，并转化为字符串
                    //var result = response.Content.ReadAsStringAsync().Result;

                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<RootDIC>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (Jresult.code == 200 && null != Jresult && null != Jresult.data)
                        {
                            for (int i = 0; i < Jresult.data.Count; i++)
                            {

                                if (Jresult.data[i].delFlag == "false")
                                {
                                    //strdepids += "'" + Jresult.data[i].deptId + "',";

                                    list.Add(Jresult.data[i]);
                                }
                            }

                            return list;
                        }
                        else
                        {
                            return list;
                        }
                    }
                }

                //return dataItems;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        //
        public class DataItemDIC
        {
            ///// <summary>
            ///// 
            ///// </summary>
            //public string id { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string dictId { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string value { get; set; }
            ///// <summary>
            ///// 施工准备
            ///// </summary>
            //public string label { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string type { get; set; }
            ///// <summary>
            ///// 施工准备
            ///// </summary>
            //public string description { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public int sort { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string createTime { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string updateTime { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string remarks { get; set; }
            ///// <summary>
            ///// 
            ///// </summary>
            //public string delFlag { get; set; }

            /// <summary>
            /// 
            /// </summary>
            public string id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string dictId { get; set; }
            /// <summary>
            /// 建筑工程合同
            /// </summary>
            public string value { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string parentCode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string level { get; set; }
            /// <summary>
            /// 建筑工程合同
            /// </summary>
            public string remarks { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int sort { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string createTime { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string updateTime { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string delFlag { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> children { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string parentId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string identity { get; set; }
            /// <summary>
            /// JZ 建筑工程合同
            /// </summary>
            public string codeAndLabel { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string isLeaf { get; set; }
        }

        public class RootDIC
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<DataItemDIC> data { get; set; }
        }


        #endregion

        #region 获取审批状态
        public static async Task<List<SPSDataItem>> GetSPDBJavaAPI(string formCode, string userName, string pageType, int current, int size, (string, string) apiinfo)
        {
            List<string> listtype = new List<string>();
            listtype.Add("TODO");
            listtype.Add("DONE");
            listtype.Add("TRANSFER_TO");
            listtype.Add("TRANSFER_FROM");
            if (!listtype.Contains(pageType))
            {
                throw new Exception("audittype 待办类型不存在");
            }

            bool pageFlag = true;
            if (pageType.ToLower() == "todo")
            {
                pageFlag = false;
            }
            else if (pageType.ToLower() == "done" || pageType.ToLower() == "transfer_to" || pageType.ToLower() == "transfer_from")
            {
                pageFlag = true;
            }

            return await GetSPDBJavaAPI(formCode, userName, pageType, pageFlag, current, size, apiinfo);
        }


        public static async Task<List<SPSDataItem>> GetSPDBJavaAPI(string formCode, string userName, string pageType, bool pageFlag, int current, int size, (string, string) apiinfo)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                _logger.Trace("====查询审批状态==========");


                if (string.IsNullOrEmpty(formCode))
                {
                    throw new Exception("获取审批状态失败，必填项formCode校验不通过。"); //return result;
                }

                if (string.IsNullOrEmpty(userName))
                {
                    throw new Exception("GetSPDBJavaAPI，userName校验不通过。"); //return result;
                }
                if (string.IsNullOrEmpty(pageType))
                {
                    throw new Exception("GetSPDBJavaAPI，pageType校验不通过。"); //return result;
                }
                //if (string.IsNullOrEmpty(pageFlag))
                //{
                //    throw new Exception("GetSPDBJavaAPI，pageFlag校验不通过。"); //return result;
                //}

                dynamic d = new ExpandoObject();
                d.userName = userName;
                d.formCode = formCode;
                d.pageType = pageType;
                d.pageFlag = pageFlag;
                d.current = current;
                d.size = size;

                //if (!getpending)
                //{
                //    List<string> businessIdList = new List<string>();

                //    for (int i = 0; i < businessIdLists.Count; i++)
                //    {
                //        if (!string.IsNullOrEmpty(businessIdLists[i]))
                //        {
                //            businessIdList.Add(businessIdLists[i]);
                //        }
                //    }

                //    //如果全是空值
                //    if (businessIdList.Count == 0)
                //    {
                //        return new List<SPSDataItem>();
                //    }

                //    d.businessIdList = businessIdList;
                //}

                _logger.Trace(Newtonsoft.Json.JsonConvert.SerializeObject(d));

                List<DataItemDIC> list = new List<DataItemDIC>();

                string baseUrl = apiinfo.Item1;
                _logger.Trace(baseUrl);
                string strAuthorization = apiinfo.Item2;

                var url = $"{baseUrl}/api/ic-business/task/getTodo";

                url = GetIpAddressDB(baseUrl);

                _logger.Trace(url);

                using (HttpClient client = new HttpClient())
                {
                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo



                    string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(d);
                    var data = Encoding.UTF8.GetBytes(sdata);
                    var content = new ByteArrayContent(data);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await client.PostAsync(url, content);
                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;


                    _logger.Trace(result);
                    _logger.Trace("====查询审批状态==========");

                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<SPStatus>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (Jresult.code == 200 && null != Jresult && null != Jresult.data)
                        {
                            return Jresult.data;
                        }
                        else
                        {
                            return new List<SPSDataItem>();
                        }
                    }
                }

                //return dataItems;
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);
                throw new Exception(ex.Message);
            }
        }


        public static async Task<List<SPSDataItem>> GetSPStatusJavaAPI(string formCode, string userName, List<string> businessIdLists, (string, string) apiinfo, bool getdb = false)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                _logger.Trace("====查询审批状态==========");


                if (string.IsNullOrEmpty(formCode))
                {
                    throw new Exception("获取审批状态失败，必填项formCode校验不通过。"); //return result;
                }

                if (string.IsNullOrEmpty(userName))
                {
                    throw new Exception("GetSPStatusJavaAPI方法，获取userName失败。"); //return result;
                }


                dynamic d = new ExpandoObject();
                d.userName = userName;
                d.formCode = formCode;
                if (!getdb)
                {
                    List<string> businessIdList = new List<string>();

                    for (int i = 0; i < businessIdLists.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(businessIdLists[i]))
                        {
                            businessIdList.Add(businessIdLists[i]);
                        }
                    }

                    //如果全是空值
                    if (businessIdList.Count == 0)
                    {
                        return new List<SPSDataItem>();
                    }

                    d.businessIdList = businessIdList;
                }

                _logger.Trace(Newtonsoft.Json.JsonConvert.SerializeObject(d));

                List<DataItemDIC> list = new List<DataItemDIC>();

                string baseUrl = apiinfo.Item1;
                _logger.Trace(baseUrl);
                string strAuthorization = apiinfo.Item2;

                var url = $"{baseUrl}/api/ic-business/task/getTodo";
                //if (formCode!= "assets_issued")
                //{
                url = GetIpAddress2(baseUrl);
                //}
                //url = "http://118.190.140.38/api/ic-business/task/getTodo";

                _logger.Trace(url);

                using (HttpClient client = new HttpClient())
                {
                    //"Basic " +
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo



                    string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(d);
                    var data = Encoding.UTF8.GetBytes(sdata);
                    var content = new ByteArrayContent(data);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await client.PostAsync(url, content);
                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;


                    _logger.Trace(result);
                    _logger.Trace("====查询审批状态==========");

                    if (result.Contains("\"code\":1"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<SPStatus>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (Jresult.code == 200 && null != Jresult && null != Jresult.data)
                        {
                            return Jresult.data;
                        }
                        else
                        {
                            return new List<SPSDataItem>();
                        }
                    }
                }

                //return dataItems;
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);
                throw new Exception(ex.Message);
            }
        }

        public class SPSDataItem
        {
            /// <summary>
            /// 
            /// </summary>
            public string id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string processInstanceId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string businessId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string callbackInterface { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string description { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string module { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string taskId { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string approveUser { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string dealUser { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string urgeStatus { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string approveStatus { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string createTime { get; set; }


            /// <summary>
            /// 
            /// </summary>
            public bool approvalAuth { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public bool cancelAuth { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public bool restartAuth { get; set; }

            //错误处理的按钮202109
            public bool errorAuth { get; set; }

        }

        public class SPStatus
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<SPSDataItem> data { get; set; }
        }

        public class panguData
        {
            public string taskId { set; get; }
            public string instanceId { set; get; }
            public string reviewStatus { set; get; }
            public bool approvalAuth { set; get; }
            public bool cancelAuth { set; get; }
            public bool restartAuth { set; get; }

            //panguData.instanceId = spstatus.processInstanceId;
            //    panguData.reviewStatus = yspstatus;
            //    panguData.approvalAuth = spstatus.approvalAuth;
            //    panguData.cancelAuth = spstatus.cancelAuth;
            //    panguData.restartAuth = spstatus.restartAuth;
        }


        #endregion

        #region 判断有没有关联审批流

        //default
        //CommonFormCardType/getByCode/investment_plan_attach

        public static async Task<string> GetFormCodeHasJavaAPI(string formCode, (string, string) apiinfo)
        {
            Logger _logger = LogManager.GetCurrentClassLogger();
            try
            {
                //_logger.Trace("=====================发起审批=============================================");

                if (string.IsNullOrEmpty(formCode))
                {
                    throw new Exception("提交审批接口，必填项formcode校验不通过。"); //return result;
                }

                string baseUrl = apiinfo.Item1;
                string strAuthorization = apiinfo.Item2;

                //CommonFormCardType/getByCode/investment_plan_attach
                var url = $"{baseUrl}/ic-business/CommonFormCardType/getByCode/";

                url = GetIpAddress7(baseUrl) + formCode;

                _logger.Trace(url);

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                    //string sdata = Newtonsoft.Json.JsonConvert.SerializeObject(spl);
                    //var data = Encoding.UTF8.GetBytes(sdata);
                    //var content = new ByteArrayContent(data);
                    //content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var response = await client.GetAsync(url);


                    //获取请求到数据，并转化为字符串
                    var result = response.Content.ReadAsStringAsync().Result;

                    _logger.Trace(result);

                    if (!result.Contains("\"code\":200"))
                    {
                        throw new Exception(result); //return result;
                    }
                    else
                    {
                        var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<RootSFSP>(result);// result.ToJson();

                        //Jresult.data.Count
                        if (Jresult.code == 200 && null != Jresult && null != Jresult.data)
                        {

                            //_logger.Trace("=====================审批成功=============================================");

                            if (!string.IsNullOrEmpty(Jresult.data.bpmKey))
                            {
                                return "has";
                            }
                            else
                            {
                                return "hasno";
                            }
                        }
                        else
                        {
                            return "err";
                        }
                    }
                }

                //return dataItems;
            }
            catch (Exception ex)
            {
                _logger.Trace(ex.Message);

                //_logger.Trace("=====================审批结束=============================================");
                throw new Exception(ex.Message);
            }
        }

        public class DataSFSP
        {
            /// <summary>
            /// 
            /// </summary>
            public string id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string formType { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string moduleId { get; set; }
            /// <summary>
            /// 投资计划附件
            /// </summary>
            public string cardName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cardDesc { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string formUrl { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cardStyleJson { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string sort { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string bpmKey { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string status { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string createTime { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string createBy { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string updateBy { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string updateTime { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int delFlag { get; set; }
        }

        public class RootSFSP
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public DataSFSP data { get; set; }
        }
        #endregion

    }

    //public static class SPLEntExtensions
    //{
    //    public static JavaApi.SPLEnt SPLEntOpe(this JavaApi.SPLEnt ent, Action<JavaApi.SPLEnt> setupAction = null)
    //    {
    //        setupAction(ent);

    //        return ent;
    //    }
    //}
}
